from django.shortcuts import render
from mydata.models import Mydata
from django.utils.dateparse import parse_date
from django.http import HttpResponseRedirect
from django.urls import reverse

from django.shortcuts import render, reverse
from django.db.models import Q
from datetime import datetime

# from django.contrib import messages

def index(request):
    datas = Mydata.objects.all()
    # 获取所有不重复的 '检验日期'  
    distinct_dates = Mydata.objects.values_list('检验日期', flat=True).distinct()  
    # distinct_batches = Mydata.objects.values_list('批号', flat=True).distinct()
    # distinct_batches = Mydata.objects.values_list('批号', flat=True).order_by('批号').distinct()

     # 获取用户的排序选择，默认为 'asc'（从小到大）
    order = request.GET.get('order', 'asc')
    
    # 根据用户的排序选择来排序 '批号'
    distinct_batches = Mydata.objects.values_list('批号', flat=True).distinct()
    if order == 'desc':
        distinct_batches = distinct_batches.order_by('批号').reverse()
    else:
        distinct_batches = distinct_batches.order_by('批号')
    # 将它们添加到上下文中  
    context = {  
        'datas': datas,  
        'distinct_datas': distinct_dates,  # 注意这里使用 distinct_dates 而不是 distinct_datas 
        'distinct_batches': distinct_batches,
    }  
    return render(request, 'index.html', context)

def filter_by_date(request):
    if request.method == 'POST':
        # 获取提交的日期参数
        date = request.POST.get('date')
        # 如果日期参数不为空，则进行过滤
        if date:
            # 解析日期参数为 datetime 对象
            parsed_date = datetime.strptime(date, '%Y-%m-%d').date()
            # 过滤数据
            filtered_datas = Mydata.objects.filter(检验日期=parsed_date)
        else:
            filtered_datas = Mydata.objects.none()
    else:
        # 如果不是 POST 请求，重定向到首页
        return HttpResponseRedirect(reverse('index'))

    # 将过滤后的数据传递到模板中
    context = {
        'datas': filtered_datas,
    }
    return render(request, 'index.html', context)

def filter_by_batch(request):
    if request.method == 'POST':
        batch = request.POST.get('批号')
        if batch:
            filtered_datas = Mydata.objects.filter(批号=batch)
        else:
            filtered_datas = Mydata.objects.none()
    else:
        # 如果不是 POST 请求，重定向到首页
        return HttpResponseRedirect(reverse('index'))

    context = {
        'datas': filtered_datas,
    }
    return render(request, 'index.html', context)
